package com.iseastar.dianxiaosan.home.parcel;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.home.adapter.ParcelWaitMainAdapter;
import com.iseastar.dianxiaosan.model.ParcelPayBean;
import com.iseastar.dianxiaosan.model.ParcelWaitBean;
import com.iseastar.dianxiaosan.model.ParcelWaitResultBean;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.shouhuobao.station.R;

import java.util.ArrayList;
import java.util.Arrays;

import droid.frame.activity.title.TitleRes;
import droid.frame.view.xlist.SListView;

/**
 * Created by joker on 2017/6/7.
 * 带取走包裹主界面
 */
public class ParcelWaitMainActivity extends BaseActivity2 implements View.OnClickListener {

    private TextView parcelWaitNum;//待取走包裹数量
    private SListView mListView;
    private ParcelWaitMainAdapter mAdapter = null;
    private TextView mPayDetailTV;//底部包裹支付详情
    private TextView mPayMoneyTV;//需要支付的价钱
    private ArrayList<ParcelWaitResultBean> items = new ArrayList<ParcelWaitResultBean>();
    String titleStr = "共%1$d个包裹待火箭侠(快递员)揽收(%2$d个用户线下支付的包裹需要在本次揽收时付款)";
    String unPayStr = "共%1$d个包裹(%2$d个未支付)";
    String payMoneyStr = "需支付:%1$s元";
    private String[] orderIds;//未支付的订单id
    private ParcelWaitResultBean resultBean = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLoadingDialog(null);
        UserBean user = AppCache.getUser();
        AppHttp.getInstance().stationParcelWaitAlls(user.getStationId());
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.parcel_waitmain);
        super.findViewById();
        getAppTitle().setCommonTitle("待取走的包裹", new TitleRes("异常包裹", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ParcelAbnormalActivity.class);
                startActivity(intent);
            }
        }));
        parcelWaitNum = (TextView) findViewById(R.id.parcel_wait_num);// 待取走包裹数量
        mPayDetailTV = (TextView) findViewById(R.id.parcel_count);
        mPayMoneyTV = (TextView) findViewById(R.id.parcel_pay_count);
        mListView = (SListView) findViewById(R.id.listview);
        findViewById(R.id.pay_view).setOnClickListener(this);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                UserBean user = AppCache.getUser();
                AppHttp.getInstance().stationParcelWaitAlls(user.getStationId());
            }
        });
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 获取驿站点下面的订单列表（待收取的包裹）
            case MsgID.wait_take_alls:
                cancelLoadingDialog();
                onRefreshComplete();
                final ReqResult<ParcelWaitResultBean> result = JSON.parser(msg.obj, ParcelWaitResultBean.class);
                if (checkLoginStatus(result) && result.getResult() != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            items.clear();
                            resultBean = null;
                            resultBean = result.getResult();
                            if (resultBean != null) {
                                items.add(resultBean);
                            }
                            mAdapter = new ParcelWaitMainAdapter(items, getContext(), mListView);
                            int pay = (resultBean.getPayed() != null && resultBean.getPayed().size() > 0) ? resultBean.getPayed().size() : 0;
                            int unPay = (resultBean.getUnPayed() != null && resultBean.getUnPayed().size() > 0) ? resultBean.getUnPayed().size() : 0;
                            mAdapter.setCashPayedNum(unPay);
                            mAdapter.setOnLinePayNum(pay);
                            mListView.setAdapter(mAdapter);
                            if (resultBean.getUnPayed() != null && resultBean.getUnPayed().size() > 0) {
                                orderIds = new String[resultBean.getUnPayed().size()];
                                int index = 0;
                                for (ParcelWaitBean bean : resultBean.getUnPayed()) {
                                    orderIds[index] = bean.getOrderId();
                                    index++;
                                }
                            } else {
                                orderIds = null;
                            }
                            parcelWaitNum.setText(String.format(titleStr, (pay + unPay), unPay));
                            mPayDetailTV.setText(String.format(unPayStr, (pay + unPay), unPay));
                            mPayMoneyTV.setText(String.format(payMoneyStr, resultBean.getToatlPrice()));
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return false;
            case MsgID.order_submit:
                cancelLoadingDialog();
                final ReqResult<ParcelPayBean> submitResult = JSON.parser(msg.obj, ParcelPayBean.class);
                if (checkLoginStatus(submitResult)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ParcelPayBean payBean = submitResult.getResult();
                            if (payBean == null) {
                                return;
                            }
                            AppCache.setOrderId(payBean.getOrderId());
                            Intent intent = new Intent(getContext(), ParcelOrderPayTotalActivity.class);
                            intent.putExtra("payData", payBean);
                            intent.putExtra("parcelnum", orderIds.length);
                            startActivityForResult(intent, 101);
                        }
                    });
                } else {
                    showToast(submitResult.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击立即支付
            case R.id.pay_view:
                if (resultBean == null) {
                    return;
                }
                if (orderIds == null || orderIds.length == 0) {
                    showToast("没有需要支付的包裹");
                    return;
                }
                String orders = Arrays.toString(orderIds);
                String replace = orders.replace("[", "").replace(" ", "").replace("]", "");
                showLoadingDialog("");
                AppHttp.getInstance().orderSubmit(resultBean.getToatlPrice(), replace);
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 101 && resultCode == RESULT_OK) {
            showLoadingDialog(null);
            UserBean user = AppCache.getUser();
            AppHttp.getInstance().stationParcelWaitAlls(user.getStationId());
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
